#include "tcpclient.h"
#include <QtNetwork>
#include <QStringList>
#include "QMessageBox"

TcpClient::TcpClient(QObject *parent, QString ipstart, QString ipend, quint16 port, quint16 id, int timeout) : QObject(parent)
{
    client = new QTcpSocket(this);
    initialized = false;
    this->port = port;
    this->id = id;
    QString ip;

    QStringList list = ipstart.split('.');
    QString ip_part = list[3];
    int ip_part_int = ip_part.toInt();
    int ipend_part_int = ipend.split('.')[3].toInt();

    int dip = ipend_part_int - ip_part_int;

    connect(client, SIGNAL(connected()), this, SLOT(connectedToHost()));
    connect(client, SIGNAL(readyRead()), this, SLOT(readData()));
    connect(client, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(stateChanged(QAbstractSocket::SocketState)));

    bool established = false;
    int err = 0;

    do
    {
        list[3] = QString::number(ip_part_int);
        ip = list[0] + "." + list[1] + "." + list[2] + "." + list[3];
        client->connectToHost(ip, port);
        established = client->waitForConnected(timeout);
        ++ip_part_int;
        ++err;
    } while(!established && err <= dip);

    if(established == false)
        QMessageBox::information(NULL, "Connection failed", "Cannot find server");

    this->parent = parent;
}

void TcpClient::decrypt(QByteArray& data)
{
    data[0] = data[0] - data[3];
    data[1] = data[1] - data[3];
    data[2] = data[2] + data[3];
}

void TcpClient::stateChanged(QAbstractSocket::SocketState state)
{
    //if(state == QAbstractSocket::ConnectedState)
      //  QMessageBox::information(NULL, "Sate", QString::number(state));
}

void TcpClient::lunch()
{
    emit signalToLunch();
}

void TcpClient::connectedToHost()
{
    // wyslij id
    QString qs("ID=");
    qs += QString::number(id);
    QByteArray data(qs.toAscii());
    client->write(data);
}

void TcpClient::readData()
{
    if(initialized)
    {
        QByteArray data = client->readAll();
        decrypt(data);
        this->velocity = data[0];
        this->electric_field = data[1];
        this->magnetic_field = data[2];

        clientReady();
    }
    else
    {
        QByteArray data = client->readAll();
        if(data[0] == 13)
            initialized = true;
        else
        {
            client->disconnect();
            client->close();
            QMessageBox::information(NULL, tr("Bad server"), "Connection refused");
        }
    }
}

void TcpClient::sendParticle(int velocity)
{
    QString data = QString::number(this->id);
    data += "#" + QString::number(velocity);
    QByteArray dsend(data.toAscii());
    client->write(dsend);
}
